package com.demo.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.annotation.LoginFilter;
import com.demo.bean.Ret;
import com.demo.domain.Admin;
import com.demo.exception.SystemException;
import com.demo.service.AdminService;
import com.demo.ui.CommonUI;
import com.demo.ui.InfoBox;
import com.demo.util.DateUtil;
import com.demo.util.JSONUtils;
import com.demo.validator.AdminLoginValidate;
import com.mdx.mobile.commons.verfy.Md5;
import com.shopcart.domain.Store;
import com.shopcart.domain.StoreGoods;
import com.shopcart.service.OrderService;
import com.vsd.domain.AreaAgent;
import com.vsd.domain.CreditGoods;
import com.vsd.service.AreaAgentService;
import com.vsd.service.CreditGoodsService;
import com.vsd.service.StoreGoodsService;
import com.vsd.service.StoreService;
import com.vsd.service.UserService;

@Controller
@RequestMapping("manager")
public class SysController extends CoreAdminController{
	@Autowired
	private AdminService adminService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private AreaAgentService agentService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private StoreGoodsService storeGoodsService;
	@Autowired
	private CreditGoodsService creditGoodsService;
	
	private Logger logger = Logger.getLogger(SysController.class);
	
	
	@RequestMapping("/{sys}")
	public String sysLogin(@PathVariable("sys") String sys,HttpServletRequest request,Model model,HttpSession session){
		//判断是否登录
		Object admin = getCurrentUser(request);
		model.addAttribute("sys",sys);
		if(admin==null) return "login";
		//登录成功 添加首页元素
		//查找最新活动
		String roleCode = getSessionParameter("ROLE_CODE", session);
		
		List<CommonUI> boxes = getBoxes(roleCode,getSessionParameter("id", session),session);
		model.addAttribute("boxes",boxes);
		
		return sys+"/index";
	}
	
	@RequestMapping("/{sys}/go/{path}")
	@LoginFilter(validateClz=AdminLoginValidate.class)
	public String go(@PathVariable("sys") String sys,@PathVariable("path") String path,Model model,HttpServletRequest request,HttpSession session){
		model.addAttribute("sys",sys);
		model.addAttribute("path",path);
		
		logger.debug("请求路径 = " + path);
		
		for (Object paramName : request.getParameterMap().keySet()) {
			if (!StringUtils.isNotBlank((String) paramName)) {
				continue;
			}
			String paramValue = request.getParameter((String) paramName);
			model.addAttribute((String) paramName, paramValue);
		}

		if (StringUtils.isBlank(path)) {
			throw new SystemException("请输入需要请求的页面路径!");
		}
		
		return sys+"/"+path;
	}
	
	@RequestMapping("/{sys}/logout")
	public String logout(@PathVariable("sys") String sys,HttpServletRequest request,Model model,HttpSession session){
		//判断是否登录
		invalidateSession(request);
		return "redirect:/manager/"+sys;
	}
	
	@RequestMapping("/{sys}/login")
	public String login(@PathVariable("sys") String sys,String username,String password,HttpSession session,Model model,HttpServletRequest request) throws Exception{
		if(StringUtils.isBlank(username)||StringUtils.isBlank(password)) return returnWithError(model,"用户名密码不能为空");
		//判断是否登录
		password = Md5.md5(password);
		
		if(sys.equals("admin")){
			List<Admin> admins = adminService.findByUserNameAndPwd(username, password);
			if(admins.size()==0) return returnWithError(model,"用户名密码错误");
			
			Admin admin = admins.get(0);
			if(admin==null) return returnWithError(model,"用户名密码错误");
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("ROLE_CODE", admin.getRoleCode());
			map.put("id", admin.getId());
			map.put("sys", sys);
			map.put("nickName", admin.getUsername());
			map.put("username", admin.getUsername());
			map.put("time", DateUtil.dateToStr(admin.getCreateTime()));
			initLoginTime(session);
			overwriteSessionParameter(map, session);
		}else if(sys.equals("agent")){
			AreaAgent agent = agentService.findByAccountAndPassword(username, password);
			if(agent==null) return returnWithError(model,"用户名密码错误");
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("ROLE_CODE", agent.getRoleCode());
			map.put("sys", sys);
			map.put("id", agent.getId());
			map.put("nickName", agent.getAccount());
			map.put("username", agent.getAccount());
			map.put("areaCode", agent.getAreaCode());
			map.put("time", DateUtil.dateToStr(agent.getCreateTime()));
			initLoginTime(session);
			overwriteSessionParameter(map, session);
			
		}else if(sys.equals("store")){
			Store agent = storeService.findByAccountAndPassword(username, password);
			if(agent==null) return returnWithError(model,"用户名密码错误");
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("ROLE_CODE", agent.getRoleCode());
			map.put("sys", sys);
			map.put("id", agent.getId());
			map.put("nickName", agent.getName());
			map.put("username", agent.getAccount());
			map.put("areaCode", agent.getAreaCode());
			map.put("logo", agent.getLogo());
			map.put("time", DateUtil.dateToStr(agent.getCreateTime()));
			initLoginTime(session);
			overwriteSessionParameter(map, session);
		}
		
		return "redirect:/manager/"+sys;
	}
	
	
	
	private  List<CommonUI> getBoxes(String roleCode,String id,HttpSession session){
		//拼装首页快捷栏
		int c = 0 ;
		List<CommonUI> boxes = new ArrayList<>();
		if(roleCode.equals("ADMIN")||roleCode.equals("ADMINISTRATOR")){
			//今日注册用户
			c = userService.countByCreateTime(new Date());
			InfoBox box = new InfoBox();
			box.setHref("/manager/admin/go/userList");
			box.setIcon("ion ion-person-add");
			box.setBgColor("small-box bg-yellow");
			box.setInfo("今日新增注册用户");
			box.setValue(c+"");
			boxes.add(box);
			
			c = orderService.countByCreateTime(new Date());
			InfoBox box1 = new InfoBox();
			box1.setHref("/manager/admin/go/orderList");
			box1.setIcon("ion ion-bag");
			box1.setBgColor("small-box bg-aqua");
			box1.setInfo("今日付款订单");
			box1.setValue(c+"");
			boxes.add(box1);
			
		}else if(roleCode.equals("AGENT")){
			
			c = orderService.countByCreateTimeAndAreaCode(getSessionParameter("areaCode", session), new Date());
			InfoBox box1 = new InfoBox();
			box1.setHref("/manager/agent/go/orderList");
			box1.setIcon("ion ion-bag");
			box1.setBgColor("small-box bg-aqua");
			box1.setInfo("今日付款订单");
			box1.setValue(c+"");
			boxes.add(box1);
			
		}else if(roleCode.equals("store")){
			c = orderService.countByCreateTimeAndStoreId(getSessionParameter("id", session), new Date());
			InfoBox box1 = new InfoBox();
			box1.setHref("/manager/store/go/orderList");
			box1.setIcon("ion ion-bag");
			box1.setBgColor("small-box bg-aqua");
			box1.setInfo("今日付款订单");
			box1.setValue(c+"");
			boxes.add(box1);
			
		}
		
		
		return boxes;
	}
	
	
	
//	private  List<CommonUI> getComments(){
//		List<CommonUI> boxes = new ArrayList<>();
//		SimpleComments box = new SimpleComments();
//		box.setHeadImg("/static/dist/img/user4-128x128.jpg");
//		box.setContent("商品有点残次，拿到手跟图片不一致");
//		box.setNickName("笑傲江湖");
//		box.setTime("12:11");
//		boxes.add(box);
//		
//		SimpleComments box1 = new SimpleComments();
//		box1.setHeadImg("/static/dist/img/user4-128x128.jpg");
//		box1.setContent("商品不错，好评！");
//		box1.setNickName("龙战于野");
//		box1.setTime("刚刚");
//		boxes.add(box1);
//		
//		return boxes;
//	}
	
	@RequestMapping("/changePwd")
	@ResponseBody
	public String changePwd(HttpServletRequest request,HttpSession session,String oldPwd,String newPwd) throws Exception{
		if(StringUtils.isBlank(newPwd)||StringUtils.isBlank(oldPwd)) return JSONUtils.serialize(new Ret(-1,"密码不能为空"));
		String account = getSessionParameter("username", session);
		String sys = getSessionParameter("sys", session);
		oldPwd = Md5.md5(oldPwd);
		if(sys.equals("admin")){
			List<Admin> admins = adminService.findByUserNameAndPwd(account, oldPwd);
			if(admins.size()==0) return JSONUtils.serialize(new Ret(-1,"旧密码不正确"));
			
			Admin admin = admins.get(0);
			if(admin==null) return JSONUtils.serialize(new Ret(-1,"旧密码不正确"));
			admin.setPassword(Md5.md5(newPwd));
			admin.setState(null);
			admin.setUsername(null);
			adminService.updateByPrimaryKeySelective(admin);
		}else if(sys.equals("agent")){
			AreaAgent agent = agentService.findByAccountAndPassword(account, oldPwd);
			if(agent==null) return JSONUtils.serialize(new Ret(-1,"旧密码不正确"));
			agent.setAccount(null);
			agent.setPassword(Md5.md5(newPwd));
			agent.setState(null);
			agentService.updateByPrimaryKeySelective(agent);
			
		}else if(sys.equals("store")){
			Store agent = storeService.findByAccountAndPassword(account, oldPwd);
			if(agent==null) return JSONUtils.serialize(new Ret(-1,"旧密码不正确"));
			agent.setAccount(null);
			agent.setPassword(Md5.md5(newPwd));
			storeService.update(agent);
		}
		
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping("/detail")
	public String detail(String id,Integer type,String title,HttpServletRequest request,Model model,HttpSession session){
		
		 	Map<String,Object> ret = new HashMap<String,Object>();
		 	if(StringUtils.isNotBlank(title)) ret.put("title", title);
		 	
			switch (type) {
			case 1:
				// type==1 商品详情
				StoreGoods goods = storeGoodsService.findById(id);
				if (goods != null) {
					ret.put("content", goods.getGoodsContent());
					model.addAttribute("obj", ret);
				} else {
					return "/error/404";
				}
				break;
			case 2:
				// type==2购买须知
				StoreGoods goods1 = storeGoodsService.findById(id);
				if (goods1 != null) {
					ret.put("content", goods1.getBeforeBuy());
					model.addAttribute("obj", ret);
				} else {
					return "/error/404";
				}
				break;
			case 3:
				// type==3 积分商品详情
				CreditGoods cg = creditGoodsService.findOne(id);
				if (cg != null) {
					ret.put("content", cg.getContent());
					model.addAttribute("obj", ret);
				} else {
					return "/error/404";
				}
				break;
			 
			default:
				break;
			}
		
		return "/detail";
	}
}
